import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'list_controller.dart';

/// 封装上拉加载更多，下拉刷新
abstract class GetxRefreshListController<T> extends GetxListController<T> {
  /// 分页第一页页码
  static const int pageNumFirst = 1;

  /// 分页条目数量
  static const int pageSize = 10;

  var _refreshController = RefreshController(initialRefresh: false);

  RefreshController get refreshController => _refreshController;

  /// 当前页码
  int _currentPageNum = pageNumFirst;

  /// 下拉刷新
  /// [init] 是否是第一次加载
  ///  true:  Error时,需要跳转页面
  ///  false: Error时,不需要跳转页面,直接给出提示
  refresh({bool init = false}) {
    // setLoading();
    try {
      _currentPageNum = pageNumFirst;
      loadData(pageNum: pageNumFirst).listen((event) {
        List<T> data = event;
        if (data.isEmpty) {
          refreshController.refreshCompleted(resetFooterState: true);
          list.clear();
          setNone();
        } else {
          onCompleted(data);
          list.clear();
          list.addAll(data);
          refreshController.refreshCompleted();
          // 小于分页的数量,禁止上拉加载更多
          if (data.length < pageSize) {
            refreshController.loadNoData();
          } else {
            //防止上次上拉加载更多失败,需要重置状态
            refreshController.loadComplete();
          }
          setSuccess();
        }
      }).onError((error) {
        print("refresh error:$error");
        setNone();
      });
    } catch (e, s) {
      print("refresh catch error");

      /// 页面已经加载了数据,如果刷新报错,不应该直接跳转错误页面
      /// 而是显示之前的页面数据.给出错误提示
      if (init) list.clear();
      refreshController.refreshFailed();
      setError(e, s);
      return null;
    }
  }

  /// 上拉加载更多
  loadMore() {
    try {
      loadData(pageNum: ++_currentPageNum).listen((event) {
        List<T> data = event;
        if (data.isEmpty) {
          _currentPageNum--;
          refreshController.loadNoData();
        } else {
          onCompleted(data);
          list.addAll(data);
          if (data.length < pageSize) {
            refreshController.loadNoData();
          } else {
            refreshController.loadComplete();
          }
        }
      }).onError((error) {
        print("refresh load more error1:$error");
        setNone();
      });
    } catch (e, s) {
      _currentPageNum--;
      refreshController.loadFailed();
      debugPrint('error--->\n' + e.toString());
      debugPrint('stack--->\n' + s.toString());
      return null;
    }
  }

  // 加载数据
  Stream loadData({int pageNum});

  void dispose() {
    _refreshController.dispose();
  }
}
